﻿Imports <xmlns:log="urn:myLogConfig">
Imports System.IO
Imports System.Threading

Public Class testAllPathsUC

    Friend r As MainWindow
    Friend lastException As Exception
    Friend stopBool As Boolean = True
    Const msg_launch = "Lancer le scan"
    Const msg_stop = "Arrêter le scan"
    Const msg_finished = "Le scan de l'ensemble des chemins est terminé"
    Const msg_cancelled = "Le scan de l'ensemble des chemins a été arrêté"

    Private _echoues As Integer
    Public Property echoues() As Integer
        Get
            Return _echoues
        End Get

        Set(ByVal value As Integer)
            _echoues = value
            lbl_echoues.Content = " /  Echoués :" & value & " )"
        End Set
    End Property

    Private _reussis As Integer
    Public Property reussis() As Integer
        Get
            Return _reussis
        End Get

        Set(ByVal value As Integer)
            _reussis = value
            lbl_reussis.Content = "Tests chemins ( Réussis :" & value
        End Set
    End Property

    Private Sub UserControl_Loaded(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
        r = MainWindow.moiMeme
    End Sub

    Private Sub Button1_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles BTN_launchScan.Click
        If BTN_launchScan.Content = msg_launch Then
            BTN_launchScan.Content = msg_stop
            launchScan()
        Else
            BTN_launchScan.Content = msg_launch
            stopScan()
        End If
    End Sub

    Sub populate()
        Dim lesPlateformes = (From plt In r.masterDoc...<log:plateforme> Select plt).ToList

        For Each unePlateformeXml As XElement In lesPlateformes

            Dim noeudPlateforme As New TreeViewItemWithIcons

            'Ajout des plateformes a la racine du treeview
            Dim unePlateforme As New Plateforme(unePlateformeXml)

            'Ajout des serveurs a la racine du plateformes
            Dim serveursXML = unePlateformeXml.<log:serveur>

            For Each unServeurXml As XElement In serveursXML
                Dim unServeur As New Serveur(unServeurXml, unePlateforme)

                Dim noeudServeur As New TreeViewItemWithIcons

                Dim cheminsXML = unServeurXml.<log:chemin>

                For Each cheminXml As XElement In cheminsXML
                    Dim unChemin As New Chemin(cheminXml, unServeur)
                    Dim noeudChemin As New TreeViewItemWithIcons

                    noeudChemin.HeaderText = unChemin.destDossier
                    noeudChemin.Tag = unChemin
                    noeudChemin.tagXML = cheminXml
                    noeudServeur.Items.Add(noeudChemin)
                Next

                noeudServeur.HeaderText = unServeur.nom
                noeudServeur.Tag = unServeur
                noeudServeur.tagXML = unServeurXml
                noeudPlateforme.Items.Add(noeudServeur)
            Next

            noeudPlateforme.Tag = unePlateforme
            noeudPlateforme.tagXML = unePlateformeXml
            noeudPlateforme.HeaderText = unePlateforme.nom
            TreeView_alltests.Items.Add(noeudPlateforme)
        Next
    End Sub

    Sub launchScan()
        stopBool = False
        TreeView_alltests.Items.Clear()
        populate()
        echoues = 0
        reussis = 0
        loadingImg.LoadSmile(DirectCast(My.Resources.Resources.loading, System.Drawing.Bitmap))
        loadingImg.StartAnimate()

        For Each noeudPlateforme As TreeViewItemWithIcons In TreeView_alltests.Items

            Dim unePlateforme = DirectCast(noeudPlateforme.Tag, Plateforme)
            noeudPlateforme.Icon = My.Resources.ic_accept.ToImageSource
            noeudPlateforme.IsExpanded = True
            For Each noeudServeur As TreeViewItemWithIcons In noeudPlateforme.Items
                noeudServeur.IsExpanded = True
                Dim unServeur = DirectCast(noeudServeur.Tag, Serveur)
                noeudServeur.Icon = My.Resources.micro_accept.ToImageSource

                For Each noeudChemin As TreeViewItemWithIcons In noeudServeur.Items
                    Dim unChemin = DirectCast(noeudChemin.Tag, Chemin)
                    noeudChemin.Icon = My.Resources.micro_accept.ToImageSource

                    Dim noeudCheminSource As New TreeViewItemWithIcons
                    noeudCheminSource.HeaderText = "Source: " & unChemin.getFullPathSource
                    noeudChemin.Items.Add(noeudCheminSource)

                    Dim noeudCheminDestination As New TreeViewItemWithIcons
                    noeudCheminDestination.HeaderText = "Destination: " & unChemin.getFullPathDestination
                    noeudChemin.Items.Add(noeudCheminDestination)

                    '------------ Source
                    Dim sourceException = checkSourceOk(unePlateforme, unChemin)
                    updateTreeViewNodes(sourceException, noeudCheminSource, noeudChemin, noeudServeur, noeudPlateforme, unChemin.getFullPathSource)

                    '------------ Destination
                    Dim excepTestDest = checkDestinationOk(unChemin.getFullPathDestination)
                    updateTreeViewNodes(excepTestDest, noeudCheminDestination, noeudChemin, noeudServeur, noeudPlateforme, unChemin.getFullPathDestination)

                    If stopBool Then
                        Exit Sub
                    End If
                Next
            Next
        Next
        scanFinished()
    End Sub

    Sub scanFinished()
        loadingImg.LoadSmile(DirectCast(My.Resources.Resources.ic_accept, System.Drawing.Bitmap))
        BTN_launchScan.Content = msg_launch
        stopBool = True
        r.consoleOut.addItim(New ConsoleTypes.msg(msg_finished, ""))
    End Sub

    Private Function checkSourceOk(plt As Plateforme, chm As Chemin) As Exception
        Dim outException As Exception = Nothing

        Dim tstart As ThreadStart = New ThreadStart(Sub()
                                                        Try
                                                            Using New Impersonator(plt.login, plt.domain, plt.password)
                                                                pathManager.testFullAccessDirectory(chm.getFullPathSource)
                                                            End Using
                                                        Catch ex As Exception
                                                            outException = ex
                                                        End Try
                                                    End Sub)
        Dim theThread = New Thread(tstart)
        theThread.Start()

        Do Until Not theThread.IsAlive
            Thread.Sleep(10)
            r.DoEvents()
        Loop
        Return outException
    End Function

    Private Function checkDestinationOk(fullPath As String) As Exception

        Dim outException As Exception = Nothing
        Dim credArchivage = r.masterDoc...<log:credArchivage>

        Dim tstart As ThreadStart = New ThreadStart(Sub()
                                                        Try
                                                            Using New Impersonator(credArchivage.@login, credArchivage.@domain, credArchivage.@password)
                                                                pathManager.testFullAccessDirectory(fullPath)
                                                            End Using
                                                        Catch ex As Exception
                                                            outException = ex
                                                        End Try
                                                    End Sub)
        Dim theThread = New Thread(tstart)
        theThread.Start()

        Do Until Not theThread.IsAlive
            Thread.Sleep(10)
            r.DoEvents()
        Loop
        Return outException
    End Function

    Private Sub startCheck(ByRef theTread As Thread, login As String, domaine As String, password As String, fullPath As String)

        Dim tstart As ThreadStart = New ThreadStart(Sub()
                                                        Try
                                                            Using New Impersonator(login, domaine, password)
                                                                pathManager.testFullAccessDirectory(fullPath)
                                                            End Using
                                                        Catch ex As Exception
                                                            lastException = ex
                                                        End Try
                                                    End Sub)
        theTread = New Thread(tstart)
        theTread.Start()
    End Sub

    Private Sub TreeView1Item_selected(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        miniConsole.Document.Blocks.Clear()
        Dim elem As TreeViewItemWithIcons = DirectCast(e.Source, TreeViewItemWithIcons)

        If elem.Tag IsNot Nothing Then
            Select Case elem.Tag.GetType.Name
                Case GetType(String).Name
                    Dim message = DirectCast(elem.Tag, String)
                    If message.StartsWith("Accès ok:") Then
                        miniConsole.Foreground = Brushes.Green
                    Else
                        miniConsole.Foreground = Brushes.Red
                    End If
                    miniConsole.addTextPair("", message)
                Case GetType(Plateforme).Name
                    Dim plt = DirectCast(elem.Tag, Plateforme)
                    miniConsole.Foreground = Brushes.Black
                    miniConsole.addTextTitle("Plateforme")
                    miniConsole.addTextPair("Nom: ", plt.nom)
                    miniConsole.addTextPair("Destination: ", plt.destination)
                Case GetType(Serveur).Name
                    Dim srv = DirectCast(elem.Tag, Serveur)
                    miniConsole.Foreground = Brushes.Black
                    miniConsole.addTextTitle("Serveur")
                    miniConsole.addTextPair("Nom: ", srv.nom)
                    miniConsole.addTextPair("Jours de rétention: ", srv.nbJourRetention)
                Case GetType(Chemin).Name
                    Dim chm = DirectCast(elem.Tag, Chemin)
                    miniConsole.Foreground = Brushes.Black
                    miniConsole.addTextTitle("Chemin")
                    miniConsole.addTextPair("Type logs: ", chm.typeLogs)
                    miniConsole.addTextPair("Chemin source: ", chm.getFullPathSource)
                    miniConsole.addTextPair("Chemin destination: ", chm.getFullPathDestination)
            End Select
        End If

    End Sub

    Private Sub testAllPaths_Unloaded(sender As Object, e As System.Windows.RoutedEventArgs) Handles Me.Unloaded
        stopScan()
    End Sub

    Sub stopScan()
        If stopBool = False Then
            loadingImg.LoadSmile(DirectCast(My.Resources.Resources.ic_warning, System.Drawing.Bitmap))
            stopBool = True
            r.consoleOut.addItim(New ConsoleTypes.warning(msg_cancelled, ""))
        End If
    End Sub



    Sub updateTreeViewNodes(excepTest As Exception, noeudCheminSub As TreeViewItemWithIcons, noeudChemin As TreeViewItemWithIcons, noeudServeur As TreeViewItemWithIcons, noeudPlateforme As TreeViewItemWithIcons, path As String)
        If excepTest Is Nothing Then
            noeudCheminSub.Icon = My.Resources.micro_accept.ToImageSource
            noeudCheminSub.Tag = "Accès ok: " & path
            reussis += 1
        Else
            echoues += 1
            noeudCheminSub.Icon = My.Resources.micro_error.ToImageSource
            noeudChemin.Icon = My.Resources.micro_error.ToImageSource
            noeudServeur.Icon = My.Resources.micro_error.ToImageSource
            noeudPlateforme.Icon = My.Resources.ic_error.ToImageSource
            noeudCheminSub.Tag = excepTest.Message
        End If

        noeudChemin.IsExpanded = True
        noeudCheminSub.BringIntoView()
    End Sub

End Class
